package com.mcxx.modules.extremepoverty.service.impl;

import cn.hutool.core.date.DateField;
import com.mcxx.common.exception.BizException;
import com.mcxx.modules.extremepoverty.service.ExCaregiverService;
import com.mcxx.modules.miniSalvation.fundpay.service.read.FundPayReadService;
import com.mcxx.modules.miniSalvation.order.dto.OrderSuspendCareDTO;
import com.mcxx.modules.miniSalvation.order.entity.OrderCareLinkEntity;
import com.mcxx.modules.miniSalvation.order.entity.OrderEntity;
import com.mcxx.modules.miniSalvation.order.entity.OrderSuspendCareEntity;
import com.mcxx.modules.miniSalvation.order.service.read.OrderReadService;
import com.mcxx.modules.miniSalvation.order.service.read.OrderSuspendCareReadService;
import com.mcxx.modules.miniSalvation.order.service.write.OrderSuspendCareWriteService;
import com.mcxx.redis.client.RedisClusterUtils;
import com.mcxx.result.BaseResult;
import com.mcxx.util.Constant;
import com.mcxx.util.DateUtil;
import com.mcxx.util.FailureCode;
import com.yinhai.ta404.core.security.vo.UserAccountVo;
import com.yinhai.ta404.core.service.BaseService;
import com.yinhai.ta404.core.transaction.annotation.TaTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service("exCaregiverService")
@TaTransactional
public class ExCaregiverServiceImpl extends BaseService implements ExCaregiverService {
    @Autowired
    private FundPayReadService fundPayReadService;
    @Autowired
    private OrderReadService orderReadService;
    @Autowired
    private OrderSuspendCareWriteService suspendCareWriteService;
    @Autowired
    private RedisClusterUtils redisClusterUtils;
    @Autowired
    private OrderSuspendCareReadService orderSuspendCareReadService;


    @Override
    public Map<String, String> findFundPayDate(String orderId) {
        Map<String,String> res = new HashMap<>();
        res.put("msg","FAIL");
        res.put("data","");
        String now = DateUtil.getMonthString();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMM");
        try{
            List<OrderEntity> list = orderReadService.queryOrderByIds(orderId.split(","));
            if(CollectionUtils.isEmpty(list)){
                throw new BizException(FailureCode.ERR_10003);
            }
            OrderEntity orderEntity = list.get(0);


            String s = fundPayReadService.verifyFundPayStopCareThrow(Constant.BusinessCode.TEKUN, orderEntity.getAreaCode(),
                    orderEntity.getStandType(), now, orderEntity.getSupplyType(),
                    Constant.FundType.CAPITAL_FUND_PAY);
            if(StringUtils.isNotBlank(s)){

                Date date = DateUtil.str2Date(s, sdf);
                Calendar cal = Calendar.getInstance();
                cal.setTime(date);
                cal.add(Calendar.MONTH, 1);
                String dateStr = sdf1.format(cal.getTime());

                Date parse = new SimpleDateFormat("yyyy-MM-dd").parse(s);
                String dateString = sdf1.format(parse);

                res.put("msg","SUCCESS");
                res.put("new",dateStr);
                res.put("old",dateString);
                return res;
            }else{
                String saveDate = now+"01";
                Date parse = new SimpleDateFormat("yyyyMMdd").parse(saveDate);
                String dateString = sdf1.format(parse);
                res.put("new",dateString);
                return res;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return res;
    }

    @Override
    public BaseResult<Boolean> suspendCare(OrderSuspendCareDTO dto, UserAccountVo userAccountVo) {

        String memberKey = "suspendCare"+dto.getMemberId();
        String msgKey = (String) redisClusterUtils.get(memberKey);
        if(msgKey == null) {
            redisClusterUtils.set(memberKey, memberKey, 5);
        }else{
            throw new BizException("-1","该对象正在暂停护理费,请刷新列表后重试");
        }

        OrderSuspendCareEntity orderSuspendCareEntitys = orderSuspendCareReadService.getInfoByMemberId(dto.getMemberId());
        if(orderSuspendCareEntitys != null){
            throw new BizException("-1","该对象护理费已暂停");
        }


        String now = DateUtil.getMonthString();
        List<OrderEntity> list = orderReadService.queryOrderByIds(dto.getOrderId().split(","));
        OrderEntity orderEntity = list.get(0);
        String s = fundPayReadService.verifyFundPayStopCareThrow(Constant.BusinessCode.TEKUN, orderEntity.getAreaCode(),
                orderEntity.getStandType(), now, orderEntity.getSupplyType(),
                Constant.FundType.CAPITAL_FUND_PAY);

        if(StringUtils.isNotBlank(s)){

            throw new BizException("-1","护理费发放名册已存在");
        }


        BaseResult<Boolean> result = new BaseResult<>();


        OrderSuspendCareEntity orderSuspendCareEntity = new OrderSuspendCareEntity();
        orderSuspendCareEntity.setId(Constant.getUUID());
        orderSuspendCareEntity.setOrderId(dto.getOrderId());
        orderSuspendCareEntity.setFamilyId(dto.getFamilyId());
        orderSuspendCareEntity.setMemberId(dto.getMemberId());
        orderSuspendCareEntity.setBusinessType(dto.getBusinessType());
        orderSuspendCareEntity.setStartMonth(now);
        orderSuspendCareEntity.setStatus("1");
        orderSuspendCareEntity.setAreaCode(dto.getAreaCode());
        orderSuspendCareEntity.setReason(dto.getReason());
        orderSuspendCareEntity.setCreateTime(new Date());
        orderSuspendCareEntity.setSuspendName(userAccountVo.getUsername());
        orderSuspendCareEntity.setSuspendId(userAccountVo.getUserId());
        orderSuspendCareEntity.setRemark(dto.getRemark());
        orderSuspendCareEntity.setCareSalaryNumber(dto.getCareSalaryNumber());
        suspendCareWriteService.insertIgnoreNull(orderSuspendCareEntity);



        return result;
    }


    @Override
    public BaseResult<Boolean> recoveryCare(OrderSuspendCareDTO dto, UserAccountVo userAccountVo) {


        String memberKey = "recoveryCare"+dto.getMemberId();
        String msgKey = (String) redisClusterUtils.get(memberKey);
        if(msgKey == null) {
            redisClusterUtils.set(memberKey, memberKey, 5);
        }else{
            throw new BizException("-1","该对象正在暂停护理费,请刷新列表后重试");
        }

        OrderSuspendCareEntity orderSuspendCareEntitys = orderSuspendCareReadService.getInfoByMemberId(dto.getMemberId());
        if(orderSuspendCareEntitys == null){
            throw new BizException("-1","该对象护理费已恢复");
        }

        String now = DateUtil.getMonthString();
        List<OrderEntity> list = orderReadService.queryOrderByIds(dto.getOrderId().split(","));
        OrderEntity orderEntity = list.get(0);
        String s = fundPayReadService.verifyFundPayStopCareThrow(Constant.BusinessCode.TEKUN, orderEntity.getAreaCode(),
                orderEntity.getStandType(), now, orderEntity.getSupplyType(),
                Constant.FundType.CAPITAL_FUND_PAY);

        if(StringUtils.isNotBlank(s)){

            throw new BizException("-1","护理费发放名册已存在");
        }


        BaseResult<Boolean> result = new BaseResult<>();


        OrderSuspendCareEntity orderSuspendCareEntity = new OrderSuspendCareEntity();
        orderSuspendCareEntity.setId(dto.getId());
        orderSuspendCareEntity.setStatus("2");
        orderSuspendCareEntity.setRecoveryTime(new Date());
        orderSuspendCareEntity.setRecoveryName(userAccountVo.getUsername());
        orderSuspendCareEntity.setRecoveryId(userAccountVo.getUserId());
        String endMonth = cn.hutool.core.date.DateUtil.parse(now, "yyyyMM").offset(DateField.MONTH,-1).toString("yyyyMM");
        orderSuspendCareEntity.setEndMonth(endMonth);
        suspendCareWriteService.updateIgnoreNull(orderSuspendCareEntity);



        return result;
    }
}
